package com.example.spannablestring;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class StringUtile {

	public static SpannableString getWeiboContent(final Context context, final TextView tv, String source)
	{
		String regexUrl = "[a-zA-z]+://[^s]*";
		
		
		SpannableString spannableString = new SpannableString(source);
		
		/**
		 * Pattern与Matcher一起合作.Matcher类提供了对正则表达式的分组支持,
		 * 以及对正则表达式的多次匹配支持.
		 */
		
		Pattern pattern = Pattern.compile(regexUrl);
		final Matcher matcher = pattern.matcher(spannableString);
		
		if(matcher.find()) {
			tv.setMovementMethod(LinkMovementMethod.getInstance());
			matcher.reset();
		}
		
		
		while(matcher.find()) {
			String urlStr = matcher.group(0);
			
			if(urlStr != null) {
				int start = matcher.start(0);
				
				BoreClickableSpan clickableSpan = new BoreClickableSpan(context) {
					
					@Override
					public void onClick(View widget) {
						//ToastUtils.showToast(context, "话题: ", Toast.LENGTH_SHORT);
						Intent intent = new Intent();
						String data = matcher.group(0);
						Uri uri = Uri.parse(data);
						intent.setAction(Intent.ACTION_VIEW);
						intent.setData(uri);
						context.startActivity(intent);
					}
				};
				spannableString.setSpan(clickableSpan, start, start + urlStr.length(), 
						Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			}

	}
		return spannableString;
}
}
